package cn.iocoder.yudao.module.datasource.service.config;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.datasource.core.DataSourceContextHolder;
import cn.iocoder.yudao.module.datasource.core.DynamicRoutingDataSource;
import cn.iocoder.yudao.module.datasource.dal.dataobject.config.DynamicDataSourceConfigDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.datasource.enums.ErrorCodeConstants.*;

/**
 * 数据源切换服务实现类
 * 提供数据源切换的业务服务，自动检查和创建数据源连接
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class DataSourceSwitchServiceImpl implements DataSourceSwitchService {

    @Autowired(required = false)
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Autowired
    private DataSourceConfigService dataSourceConfigService;

    @Override
    public void switchTo(Long dataSourceId) {
        if (dataSourceId == null) {
            log.warn("数据源ID为空，切换到默认数据源");
            switchToDefault();
            return;
        }

        if (dynamicRoutingDataSource == null) {
            log.warn("DynamicRoutingDataSource 未初始化，使用默认数据源");
            return;
        }

        // 获取数据源配置
        DynamicDataSourceConfigDO config = dataSourceConfigService.getDataSourceConfig(dataSourceId);
        if (config == null) {
            throw exception(DATASOURCE_CONFIG_NOT_EXISTS);
        }

        if (!config.getEnabled()) {
            throw exception(DYNAMIC_DATASOURCE_SWITCH_FAILED, "数据源已禁用");
        }

        switchTo(config);
    }

    @Override
    public void switchTo(DynamicDataSourceConfigDO dataSourceConfig) {
        if (dataSourceConfig == null || dataSourceConfig.getId() == null) {
            log.warn("数据源配置为空，切换到默认数据源");
            switchToDefault();
            return;
        }

        if (dynamicRoutingDataSource == null) {
            log.warn("DynamicRoutingDataSource 未初始化，使用默认数据源");
            return;
        }

        try {
            // 检查并创建数据源
            dynamicRoutingDataSource.checkCreateDataSource(dataSourceConfig);

            // 切换到指定数据源
            String dataSourceKey = String.valueOf(dataSourceConfig.getId());
            DataSourceContextHolder.setDataSource(dataSourceKey);
            log.info("成功切换到数据源: {} ({})", dataSourceConfig.getName(), dataSourceKey);

        } catch (Exception e) {
            log.error("数据源切换失败: {} ({})", dataSourceConfig.getName(), dataSourceConfig.getId(), e);
            throw exception(DYNAMIC_DATASOURCE_SWITCH_FAILED, e.getMessage());
        }
    }

    @Override
    public void switchToDefault() {
        DataSourceContextHolder.removeDataSource();
        log.debug("已恢复到默认数据源");
    }

    @Override
    public boolean exists(Long dataSourceId) {
        if (dataSourceId == null || dynamicRoutingDataSource == null) {
            return false;
        }
        
        String dataSourceKey = String.valueOf(dataSourceId);
        return dynamicRoutingDataSource.existsDataSource(dataSourceKey);
    }

    @Override
    public String getCurrentDataSource() {
        return DataSourceContextHolder.getDataSource();
    }
}